package com.muhuahealth.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 全局handler前日期统一处理
 * @author GSK
 * @version 1.0
 * @date 2021/1/30 16:42
 */
@Configuration
public class DateConvertConfig implements Converter<String,Date> {

    private static final List<String> formats = new ArrayList<>(5);
    static {
        formats.add("yyyy-MM");
        formats.add("yyyy-MM-dd");
        formats.add("yyyy-MM-dd hh:mm");
        formats.add("yyyy-MM-dd hh:mm:ss");
        formats.add("yyyy/MM/dd hh:mm:ss");
    }
    @Override
    public Date convert(String source) {
        String value = source.trim();
        if("".equals(value)){
            return null;
        }
        if(source.matches("^\\d{4}-\\d{1,2}$")){
            return parseDate(source, formats.get(0));
        }else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")){
            return parseDate(source, formats.get(1));
        }else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")){
            return parseDate(source, formats.get(2));
        }else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")){
            return parseDate(source, formats.get(3));
        }else if(source.matches("^\\d{4}/\\d{1,2}/\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")){
            return parseDate(source, formats.get(4));
        }else {
            throw new IllegalArgumentException("Invalid boolean value '" + source + "'");
        }
    }

    /**
     *  格式化日期
     * @param dateStr
     * @param format
     * @return
     */
    public Date parseDate(String dateStr,String format){

        Date date = null;
        try{
            DateFormat dateFormat= new SimpleDateFormat();
            date = dateFormat.parse(dateStr);
        }catch (Exception e){

        }
        return date;
    }
}
